<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <div id="fullscreen" class="_layout_main_">

      <!--搜索-->
      <a-form
          ref="searchForm"
          layout="inline"
          :model="form.defSearch"
          :rules="form.defSearchRules"
          style="display: flex;flex-wrap:wrap;padding: 24px"
          class="_search_from_ ">

        <a-form-item label="API名称" name="name" class="_250w ">
          <a-auto-complete
              v-model:value="form.defSearch.name"
              placeholder="请输入API名称"
              :allowClear="true"
              :options="auto.name"
              @keyup.enter.prevent="queryPage_"
              @search="(value) => { searchAsync_( value, 'name' )}"
          >
            <template #option="item">
              <div @click="searchSelect_(item.name,'name',item)"> {{ item.name }}</div>
            </template>
          </a-auto-complete>
        </a-form-item>

        <a-form-item label="请求地址" name="path" class="_300w ">
          <a-auto-complete
              v-model:value="form.defSearch.path"
              placeholder="请输入请求地址"
              :allowClear="true"
              :options="auto.path"
              @keyup.enter.prevent="queryPage_"
              @search="(value) => { searchAsync_( value, 'path' )}"
          >
            <template #option="item">
              <div @click="searchSelect_(item.path,'path',item)"> {{ item.path }}</div>
            </template>
          </a-auto-complete>
        </a-form-item>

        <a-form-item label="状态" name="use_state" class="_200w">
          <a-select v-model:value="form.defSearch.use_state" placeholder="当前状态" :allowClear="true">
            <a-select-option value="0">启用</a-select-option>
            <a-select-option value="1">禁用</a-select-option>
          </a-select>
        </a-form-item>

        <div style="flex: 1 1 0;"/>

        <a-form-item style="margin-right: 0">
          <a-button type="primary" @click="queryPage_">查询</a-button>
          <a-button style="margin-left: 10px" @click="()=>{ resetForm_('searchForm');  }">重置</a-button>
        </a-form-item>
        <!--      <el-form-item>-->
        <!--        <el-button type="primary" @click="queryPage_">查询</el-button>-->
        <!--        <el-button @click="()=>{ resetForm_('searchForm'); queryPage_() }">重置</el-button>-->
        <!--      </el-form-item>-->
        <!--    </el-form>-->

      </a-form>

      <!--表格选项-->
      <div style="display: flex ; align-items: center;padding: 18px 24px"
           class="_magt20 go_shadow go_radius _tools_">
        <div style="color: rgba(0,0,0,.85);font-size: 16px;">查询表格</div>

        <div style="flex: 1 1 0"></div>

        <a-button type="primary" ghost size="small" @click="openAdd_(null)">新建</a-button>

        <a-divider type="vertical"/>

        <a-tooltip placement="top">
          <template #title>
            <span>批量删除</span>
          </template>
          <delete-outlined :style="{fontSize: '16px'}" @click="delDataS_"/>
        </a-tooltip>

        <a-tooltip placement="top">
          <template #title>
            <span>设 置</span>
          </template>
          <setting-outlined :style="{fontSize: '16px'}" class="_magl14"/>
        </a-tooltip>

        <a-tooltip placement="top">
          <template #title>
            <span>全 屏</span>
          </template>
          <fullscreen-outlined :style="{fontSize: '16px'}" class="_magl14" @click="fullScreen"/>
        </a-tooltip>

      </div>

      <!--表格-->
      <a-table rowKey="id"
               :columns="table.defColumn" :data-source="table.defData" :pagination="false"
               :rowSelection="{checkStrictly:false,onChange:defChange_,onSelect:defSelect_,onSelectAll:defSelectAll_}">
        <template #bodyCell="{ text, record, index, column  }">

          <template v-if="column.dataIndex === 'path'">
            <span v-if="text">{{ text }}</span>
            <span v-else>#</span>
          </template>

          <template v-if="column.dataIndex === 'use_state'">
            <a-tag v-if="text==0" color="blue" style="border-radius: 100px">已启用</a-tag>
            <a-tag v-if="text==1" color="orange" style="border-radius: 100px">已禁用</a-tag>
          </template>

          <template v-if="column.dataIndex === 'check_login'">
            <a-tag v-if="text==0" color="blue" style="border-radius: 100px">已开启</a-tag>
            <a-tag v-if="text==1" color="orange" style="border-radius: 100px">已关闭</a-tag>
          </template>

          <template v-if="column.dataIndex === 'check_permission'">
            <a-tag v-if="text==0" color="blue" style="border-radius: 100px">已开启</a-tag>
            <a-tag v-if="text==1" color="orange" style="border-radius: 100px">已关闭</a-tag>
          </template>

          <template v-if="column.dataIndex === 'level'">
            <a-tag
                :color="getLevelColor(text)"
                :style="{borderRadius: '100px'}">{{ text }}
            </a-tag>
          </template>

          <template v-if="column.dataIndex === 'action'">
            <a v-if="record.level==1" @click="openAdd_(record)">新增</a>
            <a-divider v-if="record.level==1" type="vertical"/>
            <a @click="openEdit_(record)">编辑</a>
            <a-divider type="vertical"/>
            <a-popconfirm placement="bottom" ok-text="确定" cancel-text="取消" @confirm="delDat(record)">
              <template #title>
                <p>是否执行删除操作</p>
              </template>
              <a>删除</a>
            </a-popconfirm>
          </template>

        </template>
      </a-table>

      <!--新增Dialog-->
      <a-modal
          v-model:visible="show.insertDialog"
          title="新增权限"
          width="1000px"
          :destroyOnClose="true"
          :maskClosable="false">

        <!--新增表单-->
        <a-form
            ref="defForm"
            :model="form.defData"
            :rules="form.defRules"
            :label-col="form.defLC"
            :wrapper-col="form.defWC"
            class="go_shadow go_radius">

          <a-form-item label="API名称" name="name">
            <a-input v-model:value="form.defData.name" placeholder="请输入API名称" :allowClear="true"/>
          </a-form-item>

          <a-form-item label="请求地址" name="path">
            <a-input v-model:value="form.defData.path" placeholder="请输入请求地址" :allowClear="true"/>
          </a-form-item>

          <a-form-item label="当前状态" name="use_state">
            <a-radio-group v-model:value="form.defData.use_state">
              <a-radio value="0">启用</a-radio>
              <a-radio value="1">禁用</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="登录校验" name="check_login">
            <a-radio-group v-model:value="form.defData.check_login">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="权限校验" name="check_permission">
            <a-radio-group v-model:value="form.defData.check_permission">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="重复提交校验" name="check_re_submit">
            <a-radio-group v-model:value="form.defData.check_re_submit">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="访问间隔(秒)" name="access_time">
            <a-input-number v-model:value="form.defData.access_time" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问间隔（0代表无限制）</span>
          </a-form-item>

          <a-form-item label="间隔内访问次数" name="access_max_count">
            <a-input-number v-model:value="form.defData.access_max_count" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问间隔时间内的访问次数（默认为1）</span>
          </a-form-item>

          <a-form-item label="访问总次数" name="max_count">
            <a-input-number v-model:value="form.defData.max_count" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问总次数（0代表无限制）</span>
          </a-form-item>

          <a-form-item label="排序" name="sort">
            <a-input-number v-model:value="form.defData.sort" :min="1" :max="99999"/>
          </a-form-item>

          <a-form-item label="描述信息" name="des">
            <a-textarea show-count :maxlength="200" v-model:value="form.defData.des" placeholder="请输入描述信息" :rows="3"/>
          </a-form-item>
        </a-form>

        <!--底部按钮-->
        <template #footer>
          <a-button @click="show.insertDialog = false">取消</a-button>
          <a-button class="_magl10" @click="()=>{resetForm_('defForm')}">重置</a-button>
          <a-button class="_magl10" type="primary" @click="addDat()">保存</a-button>
        </template>
      </a-modal>

      <!--编辑Dialog-->
      <a-modal
          v-model:visible="show.editDialog"
          title="编辑菜单"
          width="1000px"
          :destroyOnClose="true"
          :maskClosable="false">

        <!--编辑表单-->
        <a-form
            ref="defForm"
            :model="form.defData"
            :rules="form.defRules"
            :label-col="form.defLC"
            :wrapper-col="form.defWC"
            class="go_shadow go_radius">

          <a-form-item label="API名称" name="name">
            <a-input v-model:value="form.defData.name" placeholder="请输入API名称" :allowClear="true"/>
          </a-form-item>

          <a-form-item label="请求地址" name="path">
            <a-input v-model:value="form.defData.path" placeholder="请输入请求地址" :allowClear="true" disabled/>
          </a-form-item>

          <a-form-item label="当前状态" name="use_state">
            <a-radio-group v-model:value="form.defData.use_state">
              <a-radio value="0">已启用</a-radio>
              <a-radio value="1">已禁用</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="登录校验" name="check_login">
            <a-radio-group v-model:value="form.defData.check_login">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="权限校验" name="check_permission">
            <a-radio-group v-model:value="form.defData.check_permission">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="重复提交校验" name="check_re_submit">
            <a-radio-group v-model:value="form.defData.check_re_submit">
              <a-radio value="0">开启</a-radio>
              <a-radio value="1">关闭</a-radio>
            </a-radio-group>
          </a-form-item>


          <a-form-item label="访问间隔(秒)" name="access_time">
            <a-input-number v-model:value="form.defData.access_time" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问间隔（0代表无限制）</span>
          </a-form-item>

          <a-form-item label="间隔内访问次数" name="access_max_count">
            <a-input-number v-model:value="form.defData.access_max_count" :min="1" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问间隔时间内的访问次数（默认为1）</span>
          </a-form-item>

          <a-form-item label="访问总次数" name="max_count">
            <a-input-number v-model:value="form.defData.max_count" :min="0" :max="999999"/>
            <span style="font-size: 12px;color: #CECECE"> * 配置权限的访问总次数（0代表无限制）</span>
          </a-form-item>

          <a-form-item label="排序" name="sort">
            <a-input-number v-model:value="form.defData.sort" :min="1" :max="99999"/>
          </a-form-item>

          <a-form-item label="描述信息" name="des">
            <a-textarea show-count :maxlength="200" v-model:value="form.defData.des" placeholder="请输入描述信息" :rows="3"/>
          </a-form-item>
        </a-form>

        <!--底部按钮-->
        <template #footer>
          <a-button @click="show.editDialog = false">取消</a-button>
          <a-button class="_magl10" @click="()=>{resetForm_('defForm')}">重置</a-button>
          <a-button class="_magl10" type="primary" @click="editDat()">保存</a-button>
        </template>
      </a-modal>

    </div>
  </div>
</template>

<script>

import {createVNode, defineComponent} from 'vue';
import screenfull from "screenfull";
import {Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import Breadcrumb from "@/common/layout/Breadcrumb.vue";

export default defineComponent({
  name: 'SysAPI',
  components: {Breadcrumb,},
  mounted() {
    ////////console.log(this.$route.path, ">>>>>>mounted")
    this.queryPage_()
    //全局监听-刷新
    this.$event.$on('refresh', (data) => {
      if ('/system/api' == data['path']) {
        ////////console.log(this.$route.path, ">>>执行刷新界面>>>", data)
      }
    })

  },
  data() {
    return {
      //开关
      show: {
        //
        insertDialog: false,
        editDialog: false,
        //
        selectPMenu: false,
        selectIcon: false,
        //
        downMenu: false,
      },
      //表格
      table: {
        defData: [],
        defColumn: [
          {title: 'API名称', dataIndex: 'name', width: 220},
          {title: '请求地址', dataIndex: 'path', width: 320},
          {title: '状态', dataIndex: 'use_state', align: 'center', width: 100},
          {title: '登录校验', dataIndex: 'check_login', align: 'center', width: 100},
          {title: '权限校验', dataIndex: 'check_permission', align: 'center', width: 100},
          {title: '排序', dataIndex: 'sort', align: 'center', width: 100},
          {title: '操作', dataIndex: 'action', align: 'center', width: 200},
        ],
        defSelectKey: [],
        defSelectRow: [],
        defSize: 'middle',
      },
      //表单
      form: {
        defData: {},
        defRules: {
          pname: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          level: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          check_permission: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          check_re_submit: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          access_time: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          access_max_count: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          use_state: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          max_count: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          sort: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          name: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
          path: [
            {
              type: 'any',
              required: true,
              message: '必填项',
              trigger: 'blur',
            },
          ],
        },
        defLC: {span: 4},
        defWC: {span: 16},
        defSearch: {
          name: "",
          path: "",
          use_state: undefined,
          level: undefined,
        },
        defSearchRules: {},
        //(初始化/重置)Data
        defResetData: {
          level: '1',
          check_login: '0',
          check_permission: '0',
          check_re_submit: '1',
          access_time: '0',
          use_state: '0',
          access_max_count: '1',
          max_count: '0',
          des: '',
          pid: '0',
          sort: 100,
        },
      },
      //自动完成
      auto: {
        name: [],
      }
    };
  },
  methods: {
    queryPage_() {
      let param = {
        ...this.form.defSearch
      }
      this.$http.post('/system/api/page', param).then((res) => {
        if (res.status) {
          this.table.defData = this.$kit.getTree(res.data)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //自动完成查询
    searchAsync_(str, type) {
      // ////////////console.log("searchAsync_---" + str + '---' + type)
      this.$http.post('/system/api/searchInput', {[type]: str}).then((res) => {
        this.auto[type] = res.data
      })
    },
    //input异步查询-点击事件
    searchSelect_(value, type, item) {
      this.form.defSearch[type] = value
    },
    //执行新增
    addDat() {
      this.$refs.defForm
          .validate()
          .then(() => {
            this.$http.post("/system/api/add", this.form.defData).then((res) => {
              if (res.status) {
                this.$message.success(res.message)
                this.queryPage_()
                this.show.insertDialog = false
              } else {
                this.$message.warning(res.message)
              }
            })
          })
          .catch(error => {
            ////////////console.log('error', error);
          });
    },
    //执行编辑
    editDat() {
      this.$refs.defForm
          .validate()
          .then(() => {
            delete this.form.defData['children']
            this.$http.post("/system/api/edit", this.form.defData).then(res => {
              if (res.status) {
                this.$message.success(res.message)
                this.queryPage_()
                this.show.editDialog = false
              } else {
                this.$message.warning(res.message)
              }
            })
          }).catch(error => {
        ////////////console.log('error', error);
      });
    },
    //执行删除
    delDat(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.$http.post("/system/api/del", {ids: [row.id]}).then((res) => {
        if (res.status) {
          this.$message.success(res.message)
          this.queryPage_()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    delDataS_() {
      if (this.table.defSelectKey.length === 0) {
        this.$message.warn("请至少勾选一项", 1)
        return
      }
      Modal.confirm({
        title: '是否确定删除?',
        icon: createVNode(ExclamationCircleOutlined),
        content: `已勾选${this.table.defSelectKey.length}条数据`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          this.$http.post("/system/api/del", {ids: this.table.defSelectKey}).then((res) => {
            if (res.status) {
              this.$message.success(res.message)
              this.queryPage_()
            } else {
              this.$message.warning(res.message)
            }
          })
        },
        onCancel: () => {
          this.$message.warning("操作已取消", 1)
        },
      });
    },
    //打开新增
    openAdd_(obj) {
      this.show.insertDialog = true
      this.defResetData()

      //随便任意层级新增
      if (!obj) {
        this.form.defData.pid = "0";
        this.form.defData.pname = "#";
        return
      }

      //添加到指定父级之下
      let row = JSON.parse(JSON.stringify(obj))
      this.form.defData.pid = row.id;
      this.form.defData.pname = row.name;
      this.form.defData.level = row.level * 1 + 1;
      this.form.defData.sort = row.sort * 1 + 10;
    },
    //打开编辑
    openEdit_(obj) {
      let row = JSON.parse(JSON.stringify(obj))
      this.show.editDialog = true
      this.form.defData = row;
    },
    //选择菜单
    selectPMenu(obj) {
      //根请求地址
      if (!obj) {
        this.form.defData.pid = "0";
        this.form.defData.pname = "#";
        this.form.defData.level = "1";
        this.show.selectPMenu = false;
        return
      }
      //添加到指定父级之下
      let row = JSON.parse(JSON.stringify(obj))
      this.form.defData.pid = row.id;
      this.form.defData.pname = row.name;
      this.form.defData.level = row.level * 1 + 1;
      this.show.selectPMenu = false;
    },
    //重置表单
    resetForm_(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    //初始化表单
    defResetData() {
      this.form.defData = JSON.parse(JSON.stringify(this.form.defResetData))
    },
    //表格多选
    defChange_(selectedRowKeys, selectedRows) {
      this.table.defSelectKey = selectedRowKeys
      this.table.defSelectRow = selectedRows
      ////////////console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    defSelect_(record, selected, selectedRows) {
    },
    defSelectAll_(selected, selectedRows, changeRows) {
    },
    //全屏
    fullScreen() {
      let element = document.getElementById("fullscreen")
      if (screenfull.isEnabled) {
        screenfull.request(element)
      }
      screenfull.toggle()
    },
    getLevelColor(text) {
      if (text == 1) return '#006d75'
      if (text == 2) return '#13c2c2'
      if (text == 3) return '#52c41a'
      if (text == 4) return '#69c0ff'
      return '#bae7ff'
    },
  }

});
</script>

<style lang="less">

</style>

<style scoped lang="less">

</style>
